<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>管理页面</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css">
    <link rel="stylesheet" href="https://unpkg.com/bootstrap-table@1.20.0/dist/bootstrap-table.min.css">
    <style>
      body{
        background-color: #f8f8f8;
        padding: 1rem;
      }
      .search {
        padding: 0.8rem;
        border-radius: 5px;
        margin-bottom: 1rem;
        box-shadow: 1px 1px 6px -4px black;
        background-color: #ffffff;
        font-size: 14px;
        color: #555;
        display: flex;
        align-items: center;
      }
      #table{
        background-color: #ffffff;
      }
      .btn{color: #fff !important;}
      .btn-success{background-color: #1ab394 !important;}
      .btn-danger{background-color: #dc3545 !important;}
      .btn-warning{background-color: #f8ac59 !important;}
      .btn:active{opacity: 0.8;}
      .search input,.search select{
        border: 1px #aaa solid;
        border-radius: 3px;
        outline: none;
        color: #555;
        text-indent: 2px;
        min-height: 28.5px;
        min-width: 145px;
      }
      select{padding: 4px 6px;min-width: 80px;}
      thead tr{background-color: #eee;}
    </style>
  </head>
  <body>
    
    <div class="search bg-white">
      <!-- <div class="mr-2">账号：<input type="text"></div> -->
      <div class="mr-4">渠道号：<select></select></div>
      <!-- <div class="mr-4">日期：<input type="date"></div> -->
      <div class="mr-2">时间：<input type="datetime-local"></div>
      <a class="btn btn-success btn-sm mr-2" onclick="searchHandle()">搜索</a>
      <a class="btn btn-warning btn-sm" onclick="location.reload()">刷新</a>
    </div>
    <table id="table" 
      class="bg-white"
      data-show-columns="true"
      data-show-columns-toggle-all="true"
      data-show-pagination-switch="true"
      data-show-toggle="true"
    ></table>

    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>
    <script src="https://unpkg.com/bootstrap-table@1.20.0/dist/bootstrap-table.min.js"></script>
    <script src="../static/zh-CN.js"></script>

    <script>
      $(async function(){
        // 日期选择框赋值今天日期
        $('[type=date]').val(new Date().getFullYear()+'-'+(new Date().getMonth()+1+'-').padStart(3, '0')+(new Date().getDate()+'').padStart(2, '0'))
        
        // 获取数据并渲染下拉表
        await getChannelData().catch(err=>console.error('请求错误1'))
        renderSelect('select',selectData)

        // 获取数据并渲染表格
        await getTableData().catch(err=>console.error('请求错误2'))
        new Array(100).fill(0).map((v,i)=>tableData.push({ date: i, channel: 'TEST'+i, order_id: '$'+i }))
        renderTable(tableData)

        
      })


      let selectData = [{ id: 1, name: 'TEST1' },{ id: 2, name: 'TEST2' }]
      let tableData = []

      // 下拉表渲染函数
      function renderSelect(ele,data){
        let html = ['<option value="null">空</option>']
        for(let v of data){
          html.push(`<option value="${v.id}">${v.name}</option>`)
        }
        $(ele).html(html.join(""))
      }

      // 表格渲染函数
      function renderTable(data){
        let columns = [
          { field: 'ts', title: '时间戳', visible:false}, 
          { field: 'date', title: '时间', sortable:true }, 
          { field: 'channel', title: '渠道' , sortable:true}, 
          { field: 'order_id', title: '订单号', sortable:true }, 
          { field: 'post_name', title: '姓名' }, 
          { field: 'post_idnum', title: '身份证' }, 
          { field: 'post_phone', title: '联系电话' }, 
          { field: 'post_addr', title: '地址' }, 
          { field: 'phone', title: '新卡号' }
        ]
        $('#table').bootstrapTable({
          data,
          columns,
          pagination:true,
          locale:'zh-CN',
          buttons,
          buttonsClass:'info',
          buttonsOrder:['export','paginationSwitch', 'toggle', 'columns']
        })
      }

      // 搜索函数
      async function searchHandle(){
        let ele = event.target
        $(ele).addClass('disabled btn-danger')
        await getTableData($('select').val(),$('[type=date').val())
        $('#table').bootstrapTable('destroy')
        renderTable(tableData)
        $(ele).removeClass('disabled btn-danger')
      }

      // 获取下拉表数据
      async function getChannelData(){
        let res = await $.get('/manage/channeldata').catch(err=>console.error('请求错误3'))
        const {code,data} = res
        if(code || data.length<1) return

        data.map((v,i)=>{selectData[i] = {id:v.channel,name:v.channel}})
      }

      // 获取表格数据
      async function getTableData(channel,date){
        let options = {}
        if(channel && channel !== 'null') Object.assign(options,{channel:parseInt(channel)})
        if(date) Object.assign(options,{date}) 

        let res = await $.get('/manage/carddata',options).catch(err=>console.error('请求错误4'))
        const {code,data} = res
        if(code) return
        tableData = data
      }
      
      // 表头按钮组扩展表格导出按钮
      function buttons () {
        return {
          export: {
            text: 'Highlight Users',
            icon: 'fa-file-export',
            event: function () {
              let cols = []
              let chars = []
              $('#table').bootstrapTable('getVisibleColumns').map(v=>{cols.push(v.field);chars.push(v.title)})
             
              let result = tableData.map(v=>{
                let row = []
                cols.map(v1=>{
                  row.push(v[v1] == undefined ? '' : v[v1])
                }) 
                return row.join(',')
              })
              result.unshift(chars.join(','))
              // console.log(result.join('\n'))

              let uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(result.join('\n'));
              var link = document.createElement("a");
              link.href = uri;
              link.download =  "联通大王卡订单.csv";
              document.body.appendChild(link);
              link.click();
              document.body.removeChild(link);

            },
            attributes: {
              title: '导出表格'
            }
          }
        }}

    </script>

  </body>
</html>